package com.vancouver.knows.ui.fragment.homePage;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.pangu.util.StringUtil;
import com.squareup.picasso.Picasso;
import com.vancouver.knows.MainApplication;
import com.vancouver.knows.R;
import com.vancouver.knows.MainApplication.TrackerName;
import com.vancouver.knows.business.bean.HomeMenuInfo;
import com.vancouver.knows.ui.activity.MainActivity;
import com.vancouver.knows.ui.activity.WebViewActivity;
import com.vancouver.knows.ui.activity.citydiscount.CityDiscoutResultActivity;
import com.vancouver.knows.ui.activity.citydiscount.MapActivity;
import com.vancouver.knows.ui.activity.citydiscount.QrCodeBusinessActivity;
import com.vancouver.knows.ui.activity.citynews.AddPostActivity;
import com.vancouver.knows.ui.activity.userpost.UserPostActivity;
import com.vancouver.knows.util.AnalyticsConstants;
import com.vancouver.knows.util.AppUtils;
import com.vancouver.knows.business.bean.DiscountCategoryInfo;
import com.vancouver.knows.business.bean.HomeGridInfo;

public class HomepageCategoryGridView extends LinearLayout {

	private Context mContext;
	private MainApplication imContext;

	public HomepageCategoryGridView(Context context) {
		super(context);
		mContext = context;
		imContext = (MainApplication) ((Activity) getContext()).getApplication();
	}

	public HomepageCategoryGridView(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		imContext = (MainApplication) ((Activity) getContext()).getApplication();
	}

	public void init(List<HomeMenuInfo> data, List<DiscountCategoryInfo> discountCategoryInfoCache) {
		removeAllViews();
		int size = data.size();
		if (size == 0) {
			return;
		}

//		setOrientation(LinearLayout.HORIZONTAL);
//		LayoutInflater layoutInflater = LayoutInflater.from(getContext());
//
//		int minSize = AppUtils.getWindowWidth(getContext()) / 5;
//
//		View firstView = layoutInflater.inflate(R.layout.main_category_vertical_item, this, false);
//		firstView.setLayoutParams(new LayoutParams(minSize * 2, minSize * 2));
//		bindData(firstView, data.get(0), 0, discountCategoryInfoCache);
//		TextView firstDescriptionText = (TextView) firstView.findViewById(R.id.categoryDescription);
//		firstDescriptionText.setText(Html.fromHtml(mContext.getString(R.string.article_count, data.get(0).getLatestCount())));
//		addView(firstView);
//
//		View firstColumnLine = new View(getContext());
//		firstColumnLine.setBackgroundColor(getContext().getResources().getColor(R.color.line_color));
//		firstColumnLine.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT));
//		addView(firstColumnLine);
//
//		LinearLayout linearLayout = new LinearLayout(getContext());
//		linearLayout.setOrientation(VERTICAL);
//		linearLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//		addView(linearLayout);
//
//		View secondView = layoutInflater.inflate(R.layout.main_category_horizontal_item, linearLayout, false);
//		secondView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, minSize));
//		bindData(secondView, data.get(1), 1, discountCategoryInfoCache);
//		TextView secondDescriptionText = (TextView) secondView.findViewById(R.id.categoryDescription);
//		secondDescriptionText.setText(Html.fromHtml(mContext.getString(R.string.classifieds_count, data.get(1).getLatestCount())));
//		linearLayout.addView(secondView);
//
//		View firstRowLine = new View(getContext());
//		firstRowLine.setBackgroundColor(getContext().getResources().getColor(R.color.line_color));
//		firstRowLine.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
//		linearLayout.addView(firstRowLine);
//
//		LinearLayout row = new LinearLayout(getContext());
//		row.setOrientation(HORIZONTAL);
//		row.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
//		linearLayout.addView(row);
//
//		for (int i = 2; i < 5; i++) {
//			View view = layoutInflater.inflate(R.layout.menu_grid_item, row, false);
//			view.setLayoutParams(new LayoutParams(minSize, minSize));
//			bindData(view, data.get(i), i, discountCategoryInfoCache);
//			row.addView(view);
//
//			if (i < 4) {
//				View columnLine = new View(getContext());
//				columnLine.setBackgroundColor(getContext().getResources().getColor(R.color.line_color));
//				columnLine.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT));
//				row.addView(columnLine);
//			}
//		}

		int column = 4;
		setOrientation(LinearLayout.VERTICAL);
		LayoutInflater layoutInflater = LayoutInflater.from(getContext());
		LayoutParams params = new LayoutParams(0, LayoutParams.WRAP_CONTENT, 1.0f);
		//确认多少行
		int row = (size % column > 0 ? 1 : 0) + size / column;
		for (int i = 0; i < row; i++) {
			LinearLayout lLayout = new LinearLayout(getContext());
			lLayout.setOrientation(LinearLayout.HORIZONTAL);
			for (int j = 0; j < column; j++) {
				int index = i * column + j;
				View view;
				if (index >= size) {
					//空view
					view = new View(getContext());
				} else {
					view = layoutInflater.inflate(R.layout.discount_category_item, lLayout, false);
					bindData(view, data.get(index), index, discountCategoryInfoCache);
				}
				lLayout.addView(view, params);

//				if (j < column - 1) {
//					View columnLine = new View(getContext());
//					columnLine.setBackgroundColor(getContext().getResources().getColor(R.color.line_color));
//					LayoutParams rowlp = new LayoutParams(1, LayoutParams.MATCH_PARENT);
//					lLayout.addView(columnLine, rowlp);
//				}
			}
			addView(lLayout);

//			if (i < row - 1) {
//				View rowLine = new View(getContext());
//				rowLine.setBackgroundColor(getContext().getResources().getColor(R.color.line_color));
//				LayoutParams rowlp = new LayoutParams(LayoutParams.MATCH_PARENT, 1);
//				addView(rowLine, rowlp);
//			}
		}

	}

	private void bindData(View view, final HomeMenuInfo menuInfo, final int position,
			final List<DiscountCategoryInfo> discountCategoryInfoCache) {
		TextView categoryName = (TextView) view.findViewById(R.id.categoryName);
		ImageView categoryImg = (ImageView) view.findViewById(R.id.categoryImg);
		setDefaultHomeGridImage(position, categoryImg, menuInfo.getMenuIcon());
		categoryName.setText(menuInfo.getMenuTitle());
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String gridType = menuInfo.getMenuType();
				if ("news".equals(gridType)) {
					((MainActivity) mContext).showFragment(R.id.cityNewsTab, 0);

				} else if (imContext.getString(R.string.ask_question).equals(gridType)) {
					if (AppUtils.getLoginStatus(mContext)) {
						Intent intent = new Intent(mContext, AddPostActivity.class);
						intent.putExtra("type", AddPostActivity.SEEKHELP);
						mContext.startActivity(intent);
					}

				} else if ("businessmap".equals(gridType)){
					if(GooglePlayServicesUtil.isGooglePlayServicesAvailable(mContext)== ConnectionResult.SUCCESS){
						Intent intent = new Intent(mContext, MapActivity.class);
						mContext.startActivity(intent);
					}else{
						Toast.makeText(mContext,R.string.install_google_play_services,Toast.LENGTH_SHORT).show();
					}

				} else if ("event".equals(gridType)) {
					((MainActivity) mContext).onEventTabChecked(true);

				} else if ("secondhand".equals(gridType)) {
					((MainActivity) mContext).showFragment(R.id.cityNewsTab, 5);

				} else if ("restaurant".equals(gridType) || "restaurant_nearby".equals(gridType)) {
					Intent intent = new Intent(mContext, MapActivity.class);
					intent.putExtra("filter", "food");
					mContext.startActivity(intent);
				} else if ("groupbuy".equals(gridType)) {
					int pos = getDiscountCategoryPosition("全部商家", discountCategoryInfoCache);
					if (pos != -1) {
						Intent intent = new Intent(getContext(), CityDiscoutResultActivity.class);
						intent.putExtra("index", pos);
						intent.putExtra("filter", "只显示团购");
						getContext().startActivity(intent);
					}
				} else if ("business".equals(gridType)) {
					((MainActivity) mContext).showFragment(R.id.cityDiscountTab, 0);
				} else if ("userpost".equals(gridType)) {
					Intent intent = new Intent(getContext(), UserPostActivity.class);
					getContext().startActivity(intent);
				} else if ("qr_code".equals(gridType)) {
					Intent intent = new Intent(getContext(), QrCodeBusinessActivity.class);
					intent.putExtra("QR_CODE_BITMAP", AppUtils.createQrImage((Activity) getContext()));
					getContext().startActivity(intent);
				} else {
					if (!StringUtil.isEmptyString(menuInfo.getMenuUrl())) {
						Intent intent = new Intent(getContext(), WebViewActivity.class);
						intent.putExtra("url", menuInfo.getMenuUrl());
						if ("transit".equals(gridType)) {
							intent.putExtra("title", imContext.getString(R.string.bus_inquiry_title));
						} else if ("airport".equals(gridType)) {
							intent.putExtra("title", imContext.getString(R.string.flights_title));
						}
						getContext().startActivity(intent);
					}
				}

				Tracker t = imContext.getTracker(TrackerName.APP_TRACKER);
				t.setScreenName(AnalyticsConstants.CUSTOM_EVENT_VALUE_HOMEPAGE);
				t.send(new HitBuilders.EventBuilder().setCategory(AnalyticsConstants.CATEGORY_BTN)
						.setAction(AnalyticsConstants.ACTION_ONCLICK)
						.setLabel(AnalyticsConstants.LABEL_HOMEPAGE_GRID + position).build());
			}
		});
	}

	public int getDiscountCategoryPosition(String category, List<DiscountCategoryInfo> discountCategoryInfoCache) {
		if (discountCategoryInfoCache == null) {
			return -1;
		}

		if (StringUtil.isEmptyString(category)) {
			return -1;
		}

		for (int index = 0, size = discountCategoryInfoCache.size(); index < size; index++) {
			if (category.equals(discountCategoryInfoCache.get(index).getName())) {
				return index;
			}
		}

		return -1;
	}

	private void setDefaultHomeGridImage(int position, ImageView categoryImg, String imageUrl) {
		categoryImg.setBackgroundResource(0);
		if (position == 0) {
			Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.google_news_copyrighted).crossFade().into(categoryImg);
		} else if (position == 1) {
			Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.ask_question).crossFade().into(categoryImg);
		} else if (position == 2) {
			Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.mountain_biking).crossFade().into(categoryImg);
		} else if (position == 3) {
			Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.handshake).crossFade().into(categoryImg);
		} else {
			Glide.with(getContext()).load(imageUrl).placeholder(R.drawable.no_image).crossFade().into(categoryImg);
		}

	}

}
